package com.lrh.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lrh.reggie.common.R;
import com.lrh.reggie.entity.Employee;
import com.lrh.reggie.service.EmployeeService;
import lombok.experimental.PackagePrivate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

        //1、将页面提交的密码password进行md5加密处理 DigestUtils.md5DigestAsHex()
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("登陆失败，没有这个员工");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("登陆失败，密码错误");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 退出登陆
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出登陆");
    }

    /**
     * 新增员工
     * 若是添加的员工账号重复会报 Duplicate entry 'linronghui' for key 'employee.idx_username' 异常
     * <p>
     * 前端发送请求携带数据 给后端
     * 后端处理响应数据 给前端
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {

        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        /**
         * 公共字段自动填充  MyMetaObjectHandler
         */
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //获得当前登录用户的id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

//        MybatisPlus 提供的 save()
        employeeService.save(employee);

        return R.success("新增员工成功");
    }


    /**
     * 员工信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);

        Page<Employee> employeePage = employeeService.page(page, pageSize, name);
        return R.success(employeePage);
    }


    /**
     * 根据id修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        //禁用的账户ID为 1858139996456873985 但查询时出现 1858139996456874000 是因为js的精度只支持16位
        // 所以才导致修改无效  可以使用对象映射器 将数据转换成想要的格式 JacksonObjectMapper
        //  JacksonObjectMapper  中   .addSerializer(Long.class, ToStringSerializer.instance)
        //在 WebMvcConfig 类 中 扩展 消息转换器 extendMessageConverters
        log.info(employee.toString());

        /**
         * 公共字段自动填充  MyMetaObjectHandler
         */
//        Long empID = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empID);
//        employee.setUpdateTime(LocalDateTime.now());

        employeeService.updateById(employee);


        return R.success("员工信息修改成功");
    }

    /**
     * 根据ID查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){

        //created() {
        //          this.id = requestUrlParam('id')
        //          this.actionType = this.id ? 'edit' : 'add'
        //          if (this.id) {
        //            this.init()
        //          }
        //        },
//        //获取url地址上面的参数
//        function requestUrlParam(argname){
//                var url = location.href  // http://localhost:8080/backend/page/member/add.html?id=1858483119393394689
//                var arrStr = url.substring(url.indexOf("?")+1).split("&")
//        for(var i =0;i<arrStr.length;i++)
//        {
//            var loc = arrStr[i].indexOf(argname+"=")
//            if(loc!=-1){
//                return arrStr[i].replace(argname+"=","").replace("?","")
//            }
//        }
//        return ""
//}
        log.info("根据ID查询员工信息。。。");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到该员工的信息");
    }
}
